package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.Power_UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = Power_UserService.class)
@Transactional
public class Power_UserServiceImpl implements Power_UserService {

    @Autowired
    private Power_UserDao power_userDao;
    @Override    //用户查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize); //分页插件 会在执行sql语句将分页详情追加到语句之后
        Page<User> page = power_userDao.findByContion(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override    //用户添加
    public void add(User user) {
        power_userDao.add(user);
    }

                  //查询角色
    public List<Role> findRole() {
        return power_userDao.findRole();
    }

    @Override     //根据用户id查询角色与用户关联表
    public List<Integer> findrolesByUserId(Integer id) {
        return power_userDao.findrolesByUserId(id);
    }

    @Override    //添加角色 修改角色与用户的关联表
    public void edit(Integer[] roles,Integer userId) {
        //先删除角色与用户之间的多对多关系
        power_userDao.deleteAssociation(userId);
        //再进行角色与用户关系的重新关联
        this.setUserAndRole(userId,roles);
    }

    @Override    //删除用户
    public void delete(Integer userId) {
        //先删除用户与角色的多对多关系
        power_userDao.deleteAssociation(userId);
        //再删除用户
        power_userDao.deleteUser(userId);
    }

    //设置角色和用户多对多关系
    public void setUserAndRole(Integer userId,Integer[] roles){
        //设置多对多关系
        if(roles != null && roles.length > 0){
            for (Integer role : roles) {
                Map<String,Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",role);
                power_userDao.setUserAndRole(map);
            }
        }
    }
}
